<?php

// app/repository/ClubMemberRepository.php
namespace app\dao;

use app\model\ClubMemberModel;
use think\Exception;

class ClubMemberDao
{
    /**
     * 添加社团成员
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function addMember(array $data): array
    {
        // 检查是否已存在
        $exists = ClubMemberModel::where([
            'club_id' => $data['club_id'],
            'user_id' => $data['user_id']
        ])->find();

        if ($exists) {
            throw new Exception('该用户已是社团成员');
        }

        $clubMember = ClubMemberModel::create([
            'club_id' => $data['club_id'],
            'user_id' => $data['user_id'],
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $clubMember->toArray();
    }

    /**
     * 获取社团成员列表
     * @param int $clubId
     * @return array
     */
    public function getClubMembers(int $clubId): array
    {
        return ClubMemberModel::with(['user'])
            ->where('club_id', $clubId)
            ->select()
            ->toArray();
    }

    /**
     * 移除社团成员
     * @param int $clubId
     * @param int $userId
     * @return bool
     */
    public function removeMember(int $clubId, int $userId): bool
    {
        return ClubMemberModel::where([
            'club_id' => $clubId,
            'user_id' => $userId
        ])->delete();
    }
}